package com.example.shellcollector.ShowApp;

import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.shellcollector.Entity.InstalledAppUsage;
import com.example.shellcollector.R;

import java.util.List;
public class MyAdapterforshow extends RecyclerView.Adapter<MyViewholder> {
    private List<InstalledAppUsage> installedAppUsages;
    private PackageManager packageManager;
    private OnItemClickListener onItemClickListener;

    //'注入接口'
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
    //'定义点击回调'
    public interface OnItemClickListener {
        void onItemClick(int position);
    }
    public MyAdapterforshow(List<InstalledAppUsage> installedAppUsages, PackageManager packageManager){
        this.installedAppUsages = installedAppUsages;
        this.packageManager = packageManager;
    }

    @NonNull
    @Override
    public MyViewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.appcard_item, parent, false);
        MyViewholder myViewholder =new MyViewholder(view);

        return myViewholder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewholder holder, int position) {
        Drawable d = installedAppUsages.get(position).getAppIcon(packageManager);
        holder.iv.setImageDrawable(d);
        holder.tv.setText(installedAppUsages.get(position).getAppName());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null) {
                    Log.e("click", "!");
                    onItemClickListener.onItemClick(position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return installedAppUsages.size();
    }
}